<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>商家审核</span>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form">
        <el-form-item label="关键词" prop="keyword">
          <el-input 
            v-model="queryParams.keyword" 
            placeholder="请输入商家名称/联系人/电话" 
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="审核状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择审核状态" clearable>
            <el-option :label="getStatusText(AUDIT_STATUS.PENDING)" :value="AUDIT_STATUS.PENDING" />
            <el-option :label="getStatusText(AUDIT_STATUS.APPROVED)" :value="AUDIT_STATUS.APPROVED" />
            <el-option :label="getStatusText(AUDIT_STATUS.REJECTED)" :value="AUDIT_STATUS.REJECTED" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="merchantList"
        border
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="shopName" label="商家名称" min-width="150" />
        <el-table-column prop="legalPerson" label="法人" width="120" />
        <el-table-column prop="contactPhone" label="联系电话" width="120" />
        <el-table-column prop="businessLicense" label="营业执照" width="120">
          <template #default="{ row }">
            <el-link 
              type="primary" 
              :underline="false"
              v-if="row.businessLicenseImage"
              @click="handlePreviewImage(row.businessLicenseImage)"
            >
              查看图片
            </el-link>
            <span v-else>暂无</span>
          </template>
        </el-table-column>
        <el-table-column prop="auditStatus" label="审核状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.auditStatus)">
              {{ getStatusText(row.auditStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="申请时间" width="180" />
        <el-table-column label="操作" align="center" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">查看</el-button>
            <el-button 
              type="success" 
              link 
              @click="handleApprove(row)"
              v-if="row.auditStatus === AUDIT_STATUS.PENDING"
            >通过</el-button>
            <el-button 
              type="danger" 
              link 
              @click="handleReject(row)"
              v-if="row.auditStatus === AUDIT_STATUS.PENDING"
            >拒绝</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 商家详情对话框 -->
    <el-dialog
      title="商家详情"
      v-model="detailDialogVisible"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="商家名称">{{ merchantDetail.shopName }}</el-descriptions-item>
        <el-descriptions-item label="法人">{{ merchantDetail.legalPerson }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ merchantDetail.contactPhone }}</el-descriptions-item>
        <el-descriptions-item label="联系邮箱">{{ merchantDetail.contactEmail }}</el-descriptions-item>
        <el-descriptions-item label="商家地址">{{ merchantDetail.address }}</el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <el-tag :type="getStatusType(merchantDetail.auditStatus)">
            {{ getStatusText(merchantDetail.auditStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ merchantDetail.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ merchantDetail.updateTime }}</el-descriptions-item>
        <el-descriptions-item label="营业执照号">{{ merchantDetail.businessLicense }}</el-descriptions-item>
        <el-descriptions-item label="营业执照" :span="2">
          <el-image 
            v-if="merchantDetail.businessLicenseImage"
            :src="merchantDetail.businessLicenseImage" 
            :preview-src-list="[merchantDetail.businessLicenseImage]"
            fit="contain"
            style="max-width: 200px; max-height: 200px;"
          />
          <span v-else>暂无营业执照</span>
        </el-descriptions-item>
        <el-descriptions-item label="商家简介" :span="2">
          {{ merchantDetail.shopDescription || '暂无简介' }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      :title="auditForm.status === AUDIT_STATUS.APPROVED ? '审核通过' : '审核拒绝'"
      v-model="auditDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="auditFormRef"
        :model="auditForm"
        :rules="auditRules"
        label-width="100px"
      >
        <el-form-item label="审核意见" prop="comment">
          <el-input
            v-model="auditForm.comment"
            type="textarea"
            :rows="3"
            :placeholder="auditForm.status === AUDIT_STATUS.APPROVED ? '请输入通过备注' : '请输入拒绝原因'"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button 
            :type="auditForm.status === AUDIT_STATUS.APPROVED ? 'success' : 'danger'"
            @click="handleAuditSubmit"
          >确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { 
  getNonApprovedMerchants,
  searchMerchants,
  getMerchantDetail,
  auditMerchant 
} from '@/api/admin'

// 审核状态常量
const AUDIT_STATUS = {
  PENDING: 0,
  APPROVED: 1,
  REJECTED: 2
}

// 状态映射函数
const getStatusType = (status) => {
  const statusMap = {
    [AUDIT_STATUS.PENDING]: 'warning',
    [AUDIT_STATUS.APPROVED]: 'success',
    [AUDIT_STATUS.REJECTED]: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    [AUDIT_STATUS.PENDING]: '待审核',
    [AUDIT_STATUS.APPROVED]: '已通过',
    [AUDIT_STATUS.REJECTED]: '已拒绝'
  }
  return statusMap[status] || '未知状态'
}

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: '',
  status: undefined // 移除默认值，因为我们只显示待审核和已拒绝的商家
})

const loading = ref(false)
const total = ref(0)
const merchantList = ref([])

// 详情对话框
const detailDialogVisible = ref(false)
const merchantDetail = ref({})

// 审核对话框
const auditDialogVisible = ref(false)
const auditFormRef = ref()
const auditForm = reactive({
  id: '',
  status: AUDIT_STATUS.PENDING,
  comment: ''
})

// 审核表单验证规则
const auditRules = {
  comment: [
    { required: true, message: '请输入审核意见', trigger: 'blur' },
    { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
  ]
}

// 获取商家列表
const getList = async () => {
  try {
    loading.value = true
    let res
    if (queryParams.keyword) {
      res = await searchMerchants(queryParams)
      merchantList.value = res.data || []
      total.value = merchantList.value.length
    } else {
      res = await getNonApprovedMerchants(queryParams)
      merchantList.value = res.data || []
      total.value = res.data?.length || 0
    }
  } catch (error) {
    ElMessage.error(error.message || '获取商家列表失败')
    merchantList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置
const handleReset = () => {
  queryParams.keyword = ''
  queryParams.status = undefined // 重置为 undefined
  handleQuery()
}

// 查看详情
const handleView = async (row) => {
  try {
    const res = await getMerchantDetail(row.id)
    merchantDetail.value = res.data || {}
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error(error.message || '获取商家详情失败')
  }
}

// 预览图片
const handlePreviewImage = (url) => {
  if (!url) return
  const image = new Image()
  image.src = url
  const newWindow = window.open('')
  newWindow.document.write(image.outerHTML)
}

// 审核操作
const handleApprove = (row) => {
  auditForm.id = row.id
  auditForm.status = AUDIT_STATUS.APPROVED
  auditForm.comment = ''
  auditDialogVisible.value = true
}

const handleReject = (row) => {
  auditForm.id = row.id
  auditForm.status = AUDIT_STATUS.REJECTED
  auditForm.comment = ''
  auditDialogVisible.value = true
}

// 提交审核
const handleAuditSubmit = async () => {
  if (!auditFormRef.value) return
  
  await auditFormRef.value.validate(async (valid) => {
    if (valid) {
      const loadingInstance = ElLoading.service({
        lock: true,
        text: '正在提交...',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      
      try {
        await auditMerchant(auditForm.id, {
          status: auditForm.status,
          comment: auditForm.comment
        })
        
        ElMessage.success('审核操作成功')
        auditDialogVisible.value = false
        getList()
      } catch (error) {
        ElMessage.error(error.message || '审核操作失败')
      } finally {
        loadingInstance.close()
      }
    }
  })
}

// 分页
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.image-preview {
  max-width: 100%;
  max-height: 400px;
}
</style> 